package com.example.testprovider;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    ContentResolver mContResol;
    Uri mUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.id_btn_insert).setOnClickListener(this);
        findViewById(R.id.id_btn_delete).setOnClickListener(this);
        findViewById(R.id.id_btn_update).setOnClickListener(this);
        findViewById(R.id.id_btn_query).setOnClickListener(this);
        findViewById(R.id.id_btn_gettype).setOnClickListener(this);
        findViewById(R.id.id_btn_call).setOnClickListener(this);
        mContResol = MainActivity.this.getContentResolver(); //android.app.ContextImpl.ApplicationContentResolver
        mUri = Uri.parse("content://com.example.testprovider.provider/");
        mContResol.registerContentObserver(mUri, true, new TestContentObserver(new Handler()));
    }

    @RequiresApi(api = 30)
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.id_btn_insert:
//                ContentResolver contResol = MainActivity.this.getContentResolver();
//                Uri uri = Uri.parse("content://com.example.testprovider.provider/students");
                mContResol.insert(mUri, new ContentValues());
                break;
            case R.id.id_btn_delete:
                mContResol.delete(mUri, "", new String[]{""});
                break;
            case R.id.id_btn_update:
                mContResol.update(mUri, new ContentValues(),"", new String[]{""});
                break;
            case R.id.id_btn_query:
                mContResol.query(mUri, null, null, null);
                break;
            case R.id.id_btn_gettype:
                mContResol.getType(mUri);
                break;
            case R.id.id_btn_call:
                Bundle bundle = new Bundle();
                mContResol.call(mUri, "LISTEN", null, bundle);
               // mContResol.call("com.example.testprovider.provider", "HERE", null, bundle);
                break;
        }
    }

    private class TestContentObserver extends ContentObserver {//监听
        public TestContentObserver(Handler handler) {
            super(handler);
        }

        //当ContentProvier数据发生改变，则触发该函数
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            LogUtil.printLog("数据改变");
        }
    }
}
